//
//  NewOrder.m
//  RRBI
//
//  Created by kyjun on 16/4/26.
//
//

#import "NewOrder.h"
#import "Login.h"
#import "Pager.h"
#import "MOrder.h"
#import "OrderCell.h"
#import "OrderHeader.h"
#import "OrderFooter.h"
#import "OrderStoreFooter.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>

@interface NewOrder ()<OrderFooterDeleagte,DZNEmptyDataSetDelegate,DZNEmptyDataSetSource,UIAlertViewDelegate>

@property(nonatomic,strong) NSMutableArray* arrayData;

@property(nonatomic,strong) NSString* cellIdentifier;
@property(nonatomic,strong) NSString* headerIdentifier;
@property(nonatomic,strong) NSString* footerIdentitifer;
@property(nonatomic,strong) NSString* footerStoreIdentifier;

@property(nonatomic,strong) UIAlertView* cancelAlert;
@property(nonatomic,strong) UIAlertView* confirmAlert;
@property(nonatomic,strong) UIAlertView* storeConfirmAlert;
@property(nonatomic,strong) UIAlertView* callAlert;
@property(nonatomic,strong) MOrder* currentOrder;

@end

@implementation NewOrder

-(instancetype)init{
    self = [super initWithStyle:UITableViewStyleGrouped];
    if(self){
        [self.tabBarItem setImage:[UIImage imageNamed:@"tab-new-order-default"]];
        [self.tabBarItem setSelectedImage:[[UIImage imageNamed:@"tab-new-order-enter"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        [self.tabBarItem setTitle:@"新订单"];
        self.tabBarItem.tag=0;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"人人便利商家";
    self.cellIdentifier = @"OrderCell";
    self.headerIdentifier = @"OrderHeader";
    self.footerIdentitifer = @"OrderFooter";
    self.footerStoreIdentifier = @"OrderStoreFooter";
    
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    
    [self.tableView registerClass:[OrderCell class] forCellReuseIdentifier:self.cellIdentifier];
    [self.tableView registerClass:[OrderHeader class] forHeaderFooterViewReuseIdentifier:self.headerIdentifier];
    [self.tableView registerClass:[OrderFooter class] forHeaderFooterViewReuseIdentifier:self.footerIdentitifer];
    [self.tableView registerClass:[OrderStoreFooter class] forHeaderFooterViewReuseIdentifier:self.footerStoreIdentifier];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadData:) name:NotificationRemoteAt object:nil];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(!self.Identity.userInfo.isLogin){
        UINavigationController* nav = [[UINavigationController alloc]initWithRootViewController:[[Login alloc]init]];
        [self presentViewController:nav animated:YES completion:nil];
    }else{
        [self refreshDataSource];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark =====================================================  Data source
-(void)queryData{
    AFHTTPRequestOperationManager* mgr = [AFHTTPRequestOperationManager manager];
    NSString *stra = [UserModel sharedInstanced].ru_Id;
    NSDictionary* arg = @{@"ince":@"get_neworder_list",@"sid":[UserModel sharedInstanced].ru_Id};
    [mgr POST:kHost parameters:arg success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [WMHelper outPutJsonString:responseObject];
        [self.arrayData removeAllObjects];
        NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
        if(flag == 200){
            NSArray* array = [responseObject objectForKey:@"data"];
            if(![WMHelper isNULLOrnil:array]){
                [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    MOrder* item = [[MOrder alloc]initWithItem:obj];
                    [self.arrayData addObject:item];
                }];
            }
            [self.tableView reloadData];
        }else{
            [self alertHUD:[responseObject objectForKey:@"msg"]];
        }
        [self.tableView.mj_header endRefreshing];
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        [self alertHUD:@"网络异常"];
        [self.tableView.mj_header endRefreshing];
    }];
    
}

-(void)refreshDataSource{
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //WJ
        [weakSelf queryData];
    }];
    
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark =====================================================  <UITableViewDataSource>

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.arrayData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OrderCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier forIndexPath:indexPath];
    MOrder* empty =self.arrayData[indexPath.section];
    cell.arrayGoods =empty.arrayGoods;
    return cell;
}

#pragma mark =====================================================  <UITableVeiwDelegate>

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    MOrder* empty =self.arrayData[indexPath.section];
    return empty.arrayGoods.count*45.f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 150.f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    MOrder* item = self.arrayData[section];
    if([item.emptyID isEqualToString:@"-1"]){
        return 180.f;
    }else{
        if(item.isDelivery){
            return 210.f;
        }else{
            return 180.f;
        }
    }
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    OrderHeader* header =  (OrderHeader*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:self.headerIdentifier];
    [header loadData:self.arrayData[section] index:section+1];
    return header;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    MOrder* item = self.arrayData[section];
    if([item.emptyID isEqualToString:@"-1"]){
        OrderStoreFooter* footer = (OrderStoreFooter*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:self.footerStoreIdentifier];
        footer.entity = item;
        footer.delegate = self;
        return footer;
    }else{
        OrderFooter* footer = (OrderFooter*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:self.footerIdentitifer];
        footer.entity = item;
        footer.delegate = self;
        return footer;
    }
}

#pragma mark =====================================================  <OrderFooterDeleagte>
-(void)orderFooterCancel:(MOrder *)item{//商家取消订单
    self.currentOrder = item;
    [self.cancelAlert show];
}

-(void)orderFooterSend:(MOrder *)item{ //商家接单
    self.currentOrder = item;
    [self.confirmAlert show];
}

-(void)orderSended:(MOrder *)item{//商家确认送达
    self.currentOrder = item;
    [self.storeConfirmAlert show];
    
}

-(void)callDelivery:(NSString *)phone{
    self.callAlert =[[UIAlertView alloc] initWithTitle:@"是否拨打电话？" message:phone delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [self.callAlert show];
}
#pragma mark =====================================================  <UIAlertViewDelegate>
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex == 1){
        if(self.callAlert == alertView){ // 取消接单
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",alertView.message]]];
        }else{
            if (self.cancelAlert == alertView){
                self.HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
                [self.navigationController.view addSubview:self.HUD];
                self.HUD.delegate = self;
                self.HUD.minSize = CGSizeMake(135.f, 135.f);
                [self.HUD setLabelFont:[UIFont systemFontOfSize:14.f]];
                [self.HUD show:YES];
                AFHTTPRequestOperationManager* mgr = [AFHTTPRequestOperationManager manager];
                NSDictionary* arg = @{@"ince":@"cancel_shop_order",@"sid":[UserModel sharedInstanced].ru_Id,@"order_id":self.currentOrder.orderID};
                [mgr POST:kHost parameters:arg success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
                    [WMHelper outPutJsonString:responseObject];
                    NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
                    if(flag == 200){
                        [self hidHUD:[responseObject objectForKey:@"msg"]];
                        [self.tableView.mj_header beginRefreshing];
                    }else{
                        [self hidHUD:[responseObject objectForKey:@"msg"]];
                    }
                } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
                    [self hidHUD:@"网络异常"];
                }];
                
            }else if(self.confirmAlert == alertView){ // 确认接单
                
                self.HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
                [self.navigationController.view addSubview:self.HUD];
                self.HUD.delegate = self;
                self.HUD.minSize = CGSizeMake(135.f, 135.f);
                [self.HUD setLabelFont:[UIFont systemFontOfSize:14.f]];
                [self.HUD show:YES];
                AFHTTPRequestOperationManager* mgr = [AFHTTPRequestOperationManager manager];
                NSDictionary* arg = @{@"ince":@"confirm_shop_order",@"sid":[UserModel sharedInstanced].ru_Id,@"order_id":self.currentOrder.orderID};
                [mgr POST:kHost parameters:arg success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
                    [WMHelper outPutJsonString:responseObject];
                    NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
                    if(flag == 200){
                        [self hidHUD:[responseObject objectForKey:@"msg"]];
                        [self.tableView.mj_header beginRefreshing];
                    }else{
                        [self hidHUD:[responseObject objectForKey:@"msg"]];
                    }
                } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
                    
                    NSLog( @"%@",error);
                    [self hidHUD:@"网络异常"];
                    
                }];
                
            }else if(self.storeConfirmAlert == alertView){
                self.HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
                [self.navigationController.view addSubview:self.HUD];
                self.HUD.delegate = self;
                self.HUD.minSize = CGSizeMake(135.f, 135.f);
                [self.HUD setLabelFont:[UIFont systemFontOfSize:14.f]];
                [self.HUD show:YES];
                AFHTTPRequestOperationManager* mgr = [AFHTTPRequestOperationManager manager];
                NSDictionary* arg = @{@"ince":@"finish_shop_order",@"sid":[UserModel sharedInstanced].ru_Id,@"order_id":self.currentOrder.orderID};
                [mgr POST:kHost parameters:arg success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
                    [WMHelper outPutJsonString:responseObject];
                    NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
                    if(flag == 200){
                        [self hidHUD:[responseObject objectForKey:@"msg"]];
                        [self.tableView.mj_header beginRefreshing];
                    }else{
                        [self hidHUD:[responseObject objectForKey:@"msg"]];
                    }
                } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
                    [self hidHUD:@"网络异常"];
                }];
            }
        }
    }
}
#pragma mark =====================================================  DZEmptyData 协议实现
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    return [[NSAttributedString alloc] initWithString:@"暂无新订单" attributes:@{NSFontAttributeName :[UIFont boldSystemFontOfSize:17.0],NSForegroundColorAttributeName:[UIColor grayColor]}];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
{
    return roundf(self.tableView.frame.size.height/10.0);
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}

#pragma mark =====================================================  Notification
-(void)reloadData:(NSNotification*)notification{
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark =====================================================  property package
-(NSMutableArray *)arrayData{
    if(!_arrayData){
        _arrayData = [[NSMutableArray alloc]init];
    }
    return _arrayData;
}

-(UIAlertView *)cancelAlert{
    if(!_cancelAlert){
        _cancelAlert = [[UIAlertView alloc] initWithTitle:nil message: @"确认取消订单?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    }
    return _cancelAlert;
}
-(UIAlertView *)confirmAlert{
    if(!_confirmAlert){
        _confirmAlert = [[UIAlertView alloc] initWithTitle:nil message: @"确认发货?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    }
    return _confirmAlert;
}

-(UIAlertView *)storeConfirmAlert{
    if(!_storeConfirmAlert){
        _storeConfirmAlert = [[UIAlertView alloc] initWithTitle:nil message: @"确认送达?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    }
    return _storeConfirmAlert;
}

@end
